﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Service;
using MODEL;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Microsoft.Practices.ServiceLocation;
using GalaSoft.MvvmLight.Views;
using Common;
using System.ComponentModel;
using GalaSoft.MvvmLight.Ioc;

namespace ViewModel.StationManager
{
    public class StationElementViewModel : ViewModelBase
    {
        public ICommand AddCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand BatchDeleteCommand { get; set; }

        private List<string> m_StationTypeList;
        public List<string> StationTypeList
        {
            get { return this.m_StationTypeList; }
            set { this.m_StationTypeList = value; base.RaisePropertyChanged(() => this.StationTypeList); }
        }
        private static readonly string NonSelectedStationType = "未选择站点类型";
        private string m_CurrentStationType;
        public string CurrentStationType
        {
            get { return this.m_CurrentStationType; }
            set { this.m_CurrentStationType = value; base.RaisePropertyChanged(() => CurrentStationType); }
        }

        private List<ElementInfo> m_ElementList;
        public List<ElementInfo> ElementList
        {
            get { return this.m_ElementList; }
            set { this.m_ElementList = value; base.RaisePropertyChanged(()=>this.ElementList); }
        }

        private IElementService m_ElementService;
        
        public StationElementViewModel(IElementService elementService)
        {
            this.m_ElementService = elementService;

            this.AddCommand = new RelayCommand(ShowEditForm);
            this.DeleteCommand = new RelayCommand<int>(DeleteElement);
            this.BatchDeleteCommand = new RelayCommand(BatchDeleteElement);
            RefreshData(() => this.PropertyChanged += OnPropertyChange);
        }

        public void OnPropertyChange(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "CurrentStationType")
            {
                this.QueryElements();
            }
        }

        public void RefreshData(Action afterAction = null)
        {
            List<string> stationTypeList = new List<string> { NonSelectedStationType };
            stationTypeList.AddRange(EnumHelper.GetEnumDescriptionList(typeof(StationTypeEnum)));
            this.StationTypeList = stationTypeList;
            this.CurrentStationType = NonSelectedStationType;
            QueryElements();
            if (afterAction != null)
            {
                afterAction.Invoke();
            }
        }

        public async void QueryElements()
        {
            string stationType = string.IsNullOrEmpty(this.CurrentStationType) || this.CurrentStationType == NonSelectedStationType ? null : this.CurrentStationType;   
            this.ElementList = (await this.m_ElementService.QueryElementsAsync(stationType)).ToList();
        }

        public void ShowEditForm()
        {
            StationElementEditViewModel vm = SimpleIoc.Default.GetInstanceWithoutCaching<StationElementEditViewModel>();
            vm.ParentViewModel = this;
            this.MessengerInstance.Send(vm, "StationElement_ShowEditForm");
        }

        private async void DeleteElement(int id)
        {
            try
            {
                bool IsConfirm = await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("当前数据即将被删除，是否确认？", "提示", "确认", "取消", null);
                if (!IsConfirm)
                {
                    return;
                }
                Task task = this.m_ElementService.DeleteElementInfoAsync(new List<int> { id });
                task.Wait();
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("删除成功", "提示");
                QueryElements();
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("删除失败", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }

        private async void BatchDeleteElement()
        {
            try
            {
                List<ElementInfo> selectedElementList = this.ElementList.Where(element => element.IsChecked).ToList();
                if (!selectedElementList.SafeCheck())
                {
                    await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("未选中任何数据", "提示");
                    return;
                }

                bool isComfirm = await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("所选数据将被全部删除，是否确认？", "提示", "确认", "取消", null);
                if (!isComfirm)
                {
                    return;
                }
                Task task = this.m_ElementService.DeleteElementInfoAsync(selectedElementList.Select(element => (int)element.Id).ToList());
                task.Wait();
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("删除成功", "提示");
                QueryElements();
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("删除失败", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }
    }
}
